package com.sugon.modules.sparepart.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.sugon.cache.J2CacheUtils;
import com.sugon.dao.SparePartDao;
import com.sugon.entity.*;
import com.sugon.entity.vo.SpartPartLyStatItemVO;
import com.sugon.modules.base.consts.SysApproveStatusConst;
import com.sugon.modules.sparepart.consts.SpPlanAbcEnum;
import com.sugon.modules.sparepart.model.vo.SparePartApproveParamVO;
import com.sugon.modules.sparepart.service.ISparepartManager;
import com.sugon.modules.sys.consts.CommonConstant;
import com.sugon.modules.sys.consts.ProcessApproveStatus;
import com.sugon.modules.sys.consts.ProcessProgressStatus;
import com.sugon.modules.sys.service.INoticeManager;
import com.sugon.modules.workflow.consts.OaWorkflowProcesses;
import com.sugon.service.*;
import com.sugon.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author ： YuXD
 * @description： 备件业务Manager实现类
 * @date ： 2020-08-07 下午 2:20
 * @version: 1.0
 */
@Service
public class SparepartManagerImpl implements ISparepartManager {

    @Autowired
    private SparePartBackService sparePartBackService;
    @Autowired
    private SparePartDao sparePartDao;
    @Autowired
    private SpareStorePosService spareStorePosService;
    @Autowired
    private SparePartService sparePartService;
    @Autowired
    private SysMsgService sysMsgService;
    @Autowired
    private SysProcessInfoService processInfoService;
    @Autowired
    private SparePartOutService sparePartOutService;
    @Autowired
    private DevMaintenWorkService devMaintenWorkService;
    @Autowired
    private SparePartDevService sparePartDevService;
    @Resource
    private SparePartTransactionRecordService sparePartTransactionService;
    @Resource
    private INoticeManager noticeManager;
    @Resource
    private SysOaProcessService oaProcessService;
    @Resource
    private SparePartKeyService sparePartKeyService;

    /**
     * batchApprove
     *
     * @param sparePartApproveParam 备件审核参数
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean batchApprove(SparePartApproveParamVO sparePartApproveParam) {
        List<String> approveSparePartIdList = sparePartApproveParam.getApproveSparePartIdList();
        int totalRows = 0;
        SparePartEntity sparePart;
        // 获取审核结果
        int approveStatus = sparePartApproveParam.getStatus();
        for (String approveSparePartId : approveSparePartIdList) {
            sparePart = sparePartService.queryObject(approveSparePartId);
            Assert.notNull(sparePart, "备件不存在，请确认！");
            sparePart.setStatus(approveStatus);
            sparePart.setReserve3(sparePartApproveParam.getRemark());
            int rows = sparePartService.update(sparePart);
            if (rows > 0) {
                totalRows += rows;
                // 生成审批记录
                oaProcessService.generateProcessHandleRecord(OaWorkflowProcesses.SP_EA.getBusType(), sparePart.getId(), "备件审核", approveStatus, sparePartApproveParam.getRemark());
                // 如果审核通过
                if (approveStatus == SysApproveStatusConst.PASSED) {
                    // 如果已审批通过的备件是关键备件，那么需要直接在关键备件清单中是否存在
                    if (SpPlanAbcEnum.KEY.getValue().equals(sparePart.getPlanAbc())) {
                        sparePartKeyService.checkKeySparePart(sparePart);
                    }
                    // 保存审批记录
                    processInfoService.saveProcessInfo(null, sparePart.getId(), ProcessInfoEnum.SPA_BJGL, ProcessApproveStatus.PASSED_WITH_APPROVE, null, sparePartApproveParam.getRemark(), ProcessProgressStatus.END);
                    // 生成成审核通过提示消息
                    SysMsgEntity sysMsgEntity = new SysMsgEntity();
                    sysMsgEntity.setDataUrl("../spare/sparepart.html?Id=" + sparePart.getId());
                    sysMsgEntity.setUserId(sparePart.getCreateUser());
                    sysMsgEntity.setDataType(ProcessInfoEnum.SPA_BJGL);
                    sysMsgEntity.setDataId(sparePart.getId());
                    sysMsgEntity.setRemark(StrUtil.format(ProcessInfoEnum.SPA_BJGL.getPassedMsgTemplate()));
                    sysMsgEntity.setDataFlag(ProcessProgressStatus.END + "");
                    sysMsgService.addApproveItem(ProcessInfoEnum.SPA_BJGL, sysMsgEntity, 0);
                } else if (approveStatus == SysApproveStatusConst.NOT_PASSED) {
                    // 生成备件审核未通过流程信息
                    processInfoService.saveProcessInfo(null, sparePart.getId(), ProcessInfoEnum.SPA_BJGL, approveStatus, null, sparePartApproveParam.getRemark(), ProcessProgressStatus.ING);
                    // 1、给备件创建用户生成提示消息
                    noticeManager.generateStationMessage("备件", "备件清单", "备件审核未通过", StrUtil.format(ProcessInfoEnum.SPA_BJGL.getNotPassedMsgTemplate(), sparePart.getName(), sparePartApproveParam.getRemark()), CommonConstant.MSG_CATEGORY_2, "url", "http://erms.changan.com/erms/ermsSSO/spare/sparepart?Id=" + sparePart.getId(), sparePart.getCreateUser());
                }
            }
        }
        return totalRows == approveSparePartIdList.size();
    }

    /**
     * cancelStock
     *
     * @param sparePartBack 备件退库信息实体
     * @return
     */
    @Override
    public synchronized boolean cancelStock(SparePartBackEntity sparePartBack) {
        sparePartBack.setBackCode(J2CacheUtils.getSequence(null, Constant.SPARE_BACK));
        sparePartBack.setBackDate(DateUtil.date());
        boolean flag = sparePartBackService.save(sparePartBack) > 0;
        if (flag) {
            // 更新当前备件的实际出库数
            SparePartOutEntity sparePartOut = sparePartOutService.queryObject(sparePartBack.getOutId());
            Assert.notNull(sparePartOut, "备件出库记录不存在，请确认！");
            sparePartOut.setBackNum(sparePartOut.getBackNum() + sparePartBack.getBackNum());
            sparePartOut.setRelNum(sparePartOut.getRelNum() - sparePartBack.getBackNum());
            sparePartOutService.update(sparePartOut);
            // 实时更新备件的仓库库位库存数
            spareStorePosService.realtimeUpdateStorePosStock(sparePartBack.getPostionId());
            // 更新备件库存数
            sparePartDao.realtimeUpdateStock(sparePartBack.getPartCode());
            // 5、生成备件入库事务
            sparePartTransactionService.generateBackTransaction(sparePartBack);
        }
        return flag;
    }

    /**
     * querySpareParts
     *
     * @param params 查询参数
     * @return
     */
    @Override
    public PageUtils querySpareParts(Map<String, Object> params) {
        //判断工单是否为空
        String gdbh = params.get("gdbh") + "";
        if (StringUtils.isNotEmpty(gdbh)) {
            //不为空则进行关联查询
            DeviceInfoEntity dmwe = devMaintenWorkService.loadDevByWxgdCode(gdbh);
            //获取供应厂家
            String factory = dmwe.getDevSupply();
            String type = dmwe.getDevTypeS();
            params.put("devType", type);
            if (StringUtils.isNotEmpty(factory)) {
                params.put("factory", factory);
            }
        }
        // 找到设备关联的备件列表，如果还没有关联，那么设置一个假的ID
        String devCode = cn.hutool.core.map.MapUtil.getStr(params, "devCode");
        if (StrUtil.isNotEmpty(devCode)) {
            List<String> sparePartIdList = sparePartDevService.queryListByDevCode(devCode);
            if (CollectionUtil.isEmpty(sparePartIdList)) {
                sparePartIdList = Arrays.asList("111");
            }
            params.put("sparePartIds", sparePartIdList);
        }

        // 如果是审批遭拒状态，那么只要之前审批遭拒的记录都显示出来
        Integer status = MapUtil.getInt(params, "status");
        if (status != null && NumberUtil.equals(status, SysApproveStatusConst.NOT_PASSED)) {
            List<SysOaProcessEntity> oaProcessList = oaProcessService.list(OaWorkflowProcesses.SP_EA.getBusType(), status);
            if (CollectionUtil.isNotEmpty(oaProcessList)) {
                params.put("spIds", oaProcessList.stream().map(SysOaProcessEntity::getBusId).collect(Collectors.toList()));
            }
        }

        //查询列表数据
        Query query = new Query(params);
        List<SparePartEntity> sparePartList = sparePartService.queryList(query);
        int total = sparePartService.queryTotal(query);
        return new PageUtils(sparePartList, total, query.getLimit(), query.getPage());
    }

    /**
     * querySparePartsStock
     *
     * @param params 查询参数
     * @return
     * @throws Exception
     */
    @Override
    public PageUtils querySparePartsStock(Map<String, Object> params) throws Exception {
        //查询列表数据
        Query query = new Query(params);
        List<SpareStorePosEntity> spareStorePosList = spareStorePosService.queryList(query);
        int total = spareStorePosService.queryTotal(query);
        return new PageUtils(spareStorePosList, total, query.getLimit(), query.getPage());
    }

    @Override
    public List<SpartPartLyStatItemVO> queryLastYearLyStat(String spId, Integer lastYears) {
        List<SpartPartLyStatItemVO> yearlyLyStatItems = CollectionUtil.newArrayList();
        int year = DateUtil.year(DateUtil.date());
        for (int i = lastYears - 1; i >= 0; i--) {
            int statYear = year - i;
            Integer yealySpLyNumber = sparePartDao.countYealySpLy(spId, statYear);
            if (yealySpLyNumber == null) {
                yealySpLyNumber = 0;
            }
            yearlyLyStatItems.add(new SpartPartLyStatItemVO(statYear, yealySpLyNumber));
        }
        return yearlyLyStatItems;
    }

}
